package school.web;

import java.sql.SQLException;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import school.domain.Customer;
import school.repository.CustomerDao;
import school.web.validators.CustomerValidator;

@Controller
public class WelcomeController {
	
	private CustomerDao customerDao;

	@RequestMapping("/pub/index.htm")
	public String handleIndex() {
		return "pub/index";
	}
	
	@RequestMapping("/pub/login.htm")
	public String handleRedirect() {
		return "pub/redirect";
	}

	@RequestMapping(value = "/pub/register.htm", method = RequestMethod.GET)
	public String handleregisterForm(ModelMap map) {

		map.addAttribute("customer", new Customer());
		map.addAttribute("success", "false");
		map.addAttribute("usernameInUse", "false");
		
		return "pub/register";
	}

	@RequestMapping(value = "/pub/register.htm", method = RequestMethod.POST)
	public String handleRegister(ModelMap map, @ModelAttribute("customer") Customer customer,
			BindingResult errors) {

		System.out.println("WelcomeController test");
		CustomerValidator validator = new CustomerValidator();
		System.out.println("WelcomeController test");
		validator.validate(customer, errors);
		System.out.println("WelcomeController test");
		
		if (!errors.hasErrors()) {
			
			try {
				customerDao.addCustomer(customer);
			} catch (SQLException e) {
				map.addAttribute("customer", customer);
				System.out.println(e.getSQLState() + "," + e.getErrorCode());
				e.printStackTrace();
				
				if(e.getSQLState().contentEquals("23505")) {
					System.out.println("yes");
					map.addAttribute("usernameInUse", "true");
				}
				return "pub/register";
				
			} catch (Exception e) {
				map.addAttribute("customer", customer);
				e.printStackTrace();		
				return "pub/register";
			}
			
			map.addAttribute("usernameInUse", "false");
			map.addAttribute("success", "true");
		} else {
			map.addAttribute("usernameInUse", "false");
			map.addAttribute("success", "false");
			map.addAttribute("customer", customer);
		}
		return "pub/register";
	}

	@RequestMapping("/pub/contact.htm")
	public String handleContact() {
		return "pub/contact";
	}

	@RequestMapping("/pub/about.htm")
	public String handleAbout() {
		return "pub/about";
	}

	public CustomerDao getCustomerDao() {
		return customerDao;
	}

	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}
	
	
}
